package com.quyunshuo.module.home.activity.main

import android.content.Context
import android.content.Intent
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.viewpager2.widget.ViewPager2
import com.quyunshuo.edwinpro.base.utils.BarUtils.addMarginTopEqualStatusBarHeight
import com.quyunshuo.edwinpro.common.ui.BaseActivity
import com.quyunshuo.module.home.adapter.ViewPagerAdapter
import com.quyunshuo.module.home.databinding.HomeActivityMainBinding
import com.quyunshuo.module.home.util.AppExit
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class MainActivity : BaseActivity<HomeActivityMainBinding, HomeViewModel>() {
    companion object {
        fun newInstance(context: Context) {
            context.startActivity(Intent(context, MainActivity::class.java))
        }
    }


    /**
     * 通过 viewModels() + Hilt 获取 ViewModel 实例
     */
    override val mViewModel by viewModels<HomeViewModel>()


    override fun createVB() = HomeActivityMainBinding.inflate(layoutInflater)


    override fun HomeActivityMainBinding.initView() {
        addMarginTopEqualStatusBarHeight(viewPager)
        // 创建适配器并设置
        val adapter = ViewPagerAdapter(this@MainActivity)
        viewPager.adapter = adapter

        // 监听页面变化更新按钮状态
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> { toggleTabs(home)}
                    1->{toggleTabs(find)}
                    else -> {toggleTabs(me)}
                }
            }
        })

    }



    override fun HomeActivityMainBinding.initListener() {
        home.setOnClickListener {
            viewPager.currentItem = 0
            toggleTabs(home) }
        find.setOnClickListener {
            viewPager.currentItem = 1
            toggleTabs(find) }
        me.setOnClickListener {
            viewPager.currentItem = 2
            toggleTabs(me) }

    }

    private fun toggleTabs(home: LinearLayout) {
        // 1行重置所有状态
        unSelTabs(listOf(mBinding.home,mBinding.find,mBinding.me))

        // 1行设置选中状态
        (home as? ViewGroup)?.getChildAt(0)?.isSelected = true  // 图标
        (home as? ViewGroup)?.getChildAt(1)?.isSelected = true  // 文本
    }

    private fun unSelTabs(listOf: List<LinearLayout>) {
        listOf.forEach {
            (it as? ViewGroup)?.getChildAt(0)?.isSelected = false  // 图标
            (it as? ViewGroup)?.getChildAt(1)?.isSelected = false  // 文本
        }

    }

    override fun initObserve() {


    }


    override fun initRequestData() {

    }

    override fun onBackPressed() {
        AppExit.onBackPressed(this)
    }
}